using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GameView.Comment;
using GameView.Models;
using GameView.Services;
using GameView.Services.Comment;
using GameView.Services.Dtos.Blacklist;
using GameView.Services.Dtos.Project;
using IPPMS.Application.Dtos.CommandRecordDto;
using MaterialDesignThemes.Wpf;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;

namespace GameView.ViewModels
{
    public partial class CommandRecordAddViewModel : ObservableValidator
    {
        private List<ProjectWithGamesInfo> _projectWithGamesInfos;
        private readonly CommandService _service;
        private readonly CommandRecordService _commandRecordService;

        private readonly ProjectService _projectService;

        public CommandRecordAddViewModel(CommandService service, ProjectService projectService, CommandRecordService cm)
        {
            _service = service;
            _projectService = projectService;
            IsMerchant = StaticValues.LoginInfo.PersonInfo.RoleId != 3;
            _commandRecordService = cm;
            LoadPG().ConfigureAwait(false);
        }

        [ObservableProperty]
        private bool _isLoading = false;

        [ObservableProperty]
        private ObservableCollection<TreeNode> _nodes = [];

        [ObservableProperty]
        [NotifyDataErrorInfo]
        [Required(ErrorMessage = "选择游戏")]
        private TreeNode? _selectedNode;

        [ObservableProperty]
        private string _attachMsg;

        [ObservableProperty]
        [NotifyDataErrorInfo]
        [Required(ErrorMessage = "请选择收货人角色")]
        private int _recivertRole = 7002;

        [ObservableProperty]
        [NotifyDataErrorInfo]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        [Required(ErrorMessage = "角色名称不能为空")]
        private string _characterName = string.Empty;

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        private string _projectName = string.Empty;

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        private string _gameName = string.Empty;

        [ObservableProperty]
        private string _remark = string.Empty;

        [ObservableProperty]
        private ObservableCollection<CommandShowModel> _commandOptions;

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        [Required(ErrorMessage = "指令不能为空")]
        private CommandShowModel _selectedCommand;

        [ObservableProperty]
        private bool _isMerchant = true;

        [RelayCommand]
        private async Task RefreshList()
        {
            await LoadPG();
        }

        private async Task<bool> LoadPG()
        {
            try
            {
                IsLoading = true;
                ApiResponse<List<ProjectWithGamesInfo>> res = null;
                if (StaticValues.LoginInfo.PersonInfo.RoleId != 1)
                    res = await _projectService.GetByPersonIdHAsync();
                else
                    res = await _projectService.GetAllHAsync();
                if (res.Data.IsNullOrEmpty())
                    return false;
                _projectWithGamesInfos = res.Data;
                Nodes.Clear();
                if (IsMerchant)
                {
                    foreach (var data in _projectWithGamesInfos)
                    {
                        var p = new TreeNode() { IsParent = true, Id = data.Id, Name = data.Name, Type = 0 };
                        Nodes.Add(p);
                        foreach (var game in data.Games)
                            p.Children.Add(new() { IsParent = false, Parent = p, Type = 1, Id = game.Id, Name = game.Name, Status = (int)game.Status });
                    }
                }
                else
                {
                    foreach (var data in _projectWithGamesInfos)
                    {
                        var p = new TreeNode() { IsParent = true, Id = data.Id, Name = data.Name, Type = 0 };
                        foreach (var game in data.Games)
                            Nodes.Add(new() { IsParent = false, Parent = p, Type = 1, Id = game.Id, Name = game.Name, Status = (int)game.Status });
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"操作失败：{ex.Message}");
                return false;
            }
            finally
            {
                IsLoading = false;
            }
        }

        [RelayCommand]
        private async Task SelectedItemChanged(TreeNode value)
        {
            if (value is null)
                return;
            if (value.Parent == null)
            {
                ProjectName = value.Name;
                GameName = "";
                return;
            }
            await LoadCommand(value.Parent.Name);
            SelectedNode = value;
            if (SelectedNode.Status == 6002)
            {
                GlobalMessage.Instance.ShowWarning($"{SelectedNode.Name}已经离线，无法操作！");
                return;
            }
            ProjectName = value.Parent.Name;
            GameName = value.Name;
        }

        [RelayCommand(CanExecute = nameof(CanSubmit))]
        private async Task Submit()
        {
            var dto = new CommandRecordAddDto()
            {
                ProjectName = SelectedNode.Parent.Name,
                GameName = SelectedNode.Name,
                Command = SelectedCommand.CValue,
                CommandStr = SelectedCommand.NameCn,
                CharacterName = CharacterName,
                AttachMsg = AttachMsg,
                Remark = Remark
            };
            CharacterName = "";
            SelectedCommand = null;
            var res = await _commandRecordService.Add(dto);
            if (res == null)
            {
                GlobalMessage.Instance.ShowError($"网络异常请稍后核查充值结果！");
            }
            if (res.StatusCode == 200)
            {
                DialogHost.CloseDialogCommand.Execute(null, null);
                CharacterName = "";
                SelectedCommand = null;
            }
            else
            {
                GlobalMessage.Instance.ShowError($"操作失败：{res.Errors}");
            }
        }

        private async Task LoadCommand(string pName)
        {
            CommandOptions ??= [];
            CommandOptions.Clear();
            var res = await _service.GetListAsync(pName);
            if (res.StatusCode != 200)
            {
                GlobalMessage.Instance.ShowError(JSON.Serialize(res.Errors));
                return;
            }
            foreach (var item in res.Data)
            {
                CommandOptions.Add(item);
            }
        }

        private bool CanSubmit() => !HasErrors && SelectedNode != null && SelectedNode.Parent != null && SelectedNode.Status == 6001 && SelectedCommand != null && !CharacterName.IsNullOrEmpty();
    }
}